SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


CREATE PROCEDURE dbo.[DnnProduct_MoveTabToParent] 
	@TabId					int,
	@NewParentId			int,
	@LastModifiedByUserID	int
AS
	BEGIN
		DECLARE @OldParentId int
		SET @OldParentId = (SELECT ParentId FROM DnnProduct_Tabs WHERE TabID = @TabId)
		
		DECLARE @TabOrder int
		SET @TabOrder = (SELECT TabOrder FROM DnnProduct_Tabs WHERE TabID = @TabId)
		
		-- Get New TabOrder
		DECLARE @NewTabOrder int
		SET @NewTabOrder = (SELECT MAX(TabOrder) FROM DnnProduct_Tabs WHERE (ParentId = @NewParentId OR (ParentId IS NULL AND @NewParentId IS NULL)))
		IF @NewTabOrder IS NULL 
			SET @NewTabOrder = 1
		ELSE
			SET @NewTabOrder = @NewTabOrder + 2			
				
		BEGIN
			-- update TabOrder of Tabs with same original Parent
			UPDATE DnnProduct_Tabs
				SET TabOrder = TabOrder - 2
				WHERE (ParentId = @OldParentId OR (ParentId IS NULL AND @OldParentId IS NULL)) 
					AND TabOrder > @TabOrder

			-- Update Tab with new TabOrder
			UPDATE DnnProduct_Tabs
				SET 
					ParentId				= @NewParentId,
					TabOrder				= @NewTabOrder,
					LastModifiedByUserID	= @LastModifiedByUserID,
					LastModifiedOnDate		= GETDATE()					
				WHERE TabID = @TabId
		END
		IF @OldParentId <> @NewParentId
			BEGIN
				EXEC dbo.DnnProduct_BuildTabLevelAndPath @TabId, 1
			END
		ELSE
			BEGIN
				EXEC dbo.DnnProduct_BuildTabLevelAndPath @TabId
			END
	END

GO
